import Vue from 'vue'
import Router from 'vue-router'
/* Layout */
import Layout from '@/layout'
import store from '@/store'
import { getToken } from '@/utils/auth'

Vue.use(Router)

const publicRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: {isHome: true},
    children: [{
      path: 'dashboard',
      name: 'dashboard',
      component: () => import('@/feature/system/app/dashboard/index'),
      meta: {title: '后台首页', icon: 'el-icon-s-home', showBreadcrumb: false}
    }]
  }
]
const lastRoutes = [
  // 404 page must be placed at the end !!!
  // { path: '*', redirect: '/404', hidden: true }
]
const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({y: 0}),
  routes: [...publicRoutes]
})

export function addRoutes(routes) {
  return router.addRoutes(routes)
}

//
// export function setupRoutes() {
//   store.commit('user/SET_ROUTES', _setRoutes(router.options.routes))
// }

const router = createRouter()

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查路径是否以 .html 结尾或需要认证（所以以 .html结尾的都需要鉴权）
  const isHtmlPage = to.path.endsWith('.html')

  if (isHtmlPage) {
    // 这里替换为你的实际认证检查逻辑
    const isAuthenticated = getToken() // 例如检查 localStorage 中的 token

    if (!isAuthenticated) {
      // 未登录则重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 登录后可以跳转回原页面
      })
      return
    }
  }

  next() // 继续导航
})

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  // const newRouter = createRouter()
  // router.matcher = newRouter.matcher // reset router
}

export default router
